package com.spice.im.chat.file;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

import com.spice.im.R;
import com.spice.im.utils.ConstantValues;
import com.spice.im.utils.HeaderLayout;
import com.spice.im.utils.HeaderLayout.HeaderStyle;
import com.spice.im.utils.HeaderLayout.onMiddleImageButtonClickListener;
import com.spice.im.utils.HeaderLayout.onRightImageButtonClickListener;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;

public class FileActivity extends Activity implements OnClickListener {
	private HeaderLayout mHeaderLayout;
	//这三个路径用于一些特殊的情况
	private String root;
	private String filePath;// 当前路径
	private String oldFilePath;// 当前路径
	
	//所有弹出信息的Toast
	Toast mToast;

	// 移动复制文件时的参数
	private String oldPath;
	private String fileName;
	private int copyOrMove;// 0 1移动 2复制
	ProgressDialog pd;
	/*
	 * 复制文件完成
	 * */
	
	
	private ArrayList<HashMap<String, Object>> fileMap;// 记录当前路径中的所有文件
	private ListView lv;
	private SimpleAdapter sa;
	private TextView tv;
	private Button bt1;
	private Button bt2;
	private Button bt3;
	private Button bt4;
	private Button bt5;
	private Button bt6;
	private FileOperation fo;

	private SharedPreferences sp;
	private Editor ed;

	private Tools tool;

//	/*
//	 * 
//	 * 日志部分开始
//	 */
//
//	public static final int LOG_SIZE = 30;
//
//	public final String LOG_PATH = Environment.getExternalStorageDirectory()
//			.getPath() + "/" + "文件浏览器CFY版" + "/log";
//	public final String LOG_NAME = "file_oper.txt";
//	private SimpleAdapter logSa;
//	private ArrayList<HashMap<String, Object>> logMap;
//	private boolean LogView;
//
//	/*
//	 * 
//	 * 日志部分结束
//	 */

//	/*
//	 * 
//	 * 
//	 * 下载部分开始
//	 */
//	private MyAdapter downloadSa;
//	private ArrayList<HashMap<String, Object>> downloadMap;
	private boolean DownloadView;
//	private DataHelper dataHelper;
//	private Button add;
//	private Button download;
//	public final String DOWNLOAD_PATH = Environment
//			.getExternalStorageDirectory().getPath()
//			+ "/"
//			+ "文件浏览器CFY版"
//			+ "/Download";
//	public static ArrayList<DownloadThread> dt;
//	private SQLiteDatabase sd;
//
//	private boolean isDelete;
//
//	// private ImageButton ib;
//	/*
//	 * 
//	 * 下载部分结束
//	 */

	private boolean isSave;
	private Context mContext;

	Handler handler = new Handler() {
		String obj = null;
		int index;
		int down;
		int progress;

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			switch (msg.what) {
//			case 0://下载过程中更新ProgressBar
//				HashMap<String, Object> flag = new HashMap<String, Object>();
//				obj = msg.obj.toString();
//				index = Integer
//						.valueOf(obj.substring(obj.lastIndexOf('-') + 1));
//				down = msg.arg1;
//				Log.i("222", "down="+down);
//				int size = dt.get(index).getFileSize();
//				progress = Tools.getProportion(size + "", down);
//				flag.put("DownloadName",
//						downloadMap.get(index).get("DownloadName"));
//				flag.put("Progress", progress);
//				flag.put("Size", size);
//				downloadMap.set(index, flag);
//				// 提醒数据更新 刷新界面 !!!!!不知道能不能成功 如果不行那么要更新MyAdapter中的数据
//				downloadSa.changeProgress(index, flag);
//				break;
//			case 1:
//				// 下载完成
//				obj = msg.obj.toString();
//				index = Integer
//						.valueOf(obj.substring(obj.lastIndexOf('-') + 1));
//				ShowToast(downloadMap.get(index).get("DownloadName") + "下载完成！");
//
//				if (index != downloadMap.size() - 1) {// 重命名
//					for (int i = index + 1; i < downloadMap.size(); i++) {
//						dt.get(i).setName("DownloadThread-" + (i - 1));
//					}
//				}
//				dt.remove(index);
//				downloadMap.remove(index);
//				if (DownloadView) {
//					lv.setAdapter(downloadSa);
//				}
//				break;

			case 0x123://复制完成时
				String path = msg.obj.toString();
				if (msg.arg1 == 1) {//复制成功
					ShowToast(fileName + "复制成功！");
//					fo.writeLogFile(tool.CountDate(System.currentTimeMillis())
//							+ " " + oldPath + "/" + fileName + "复制到" + path
//							+ "  " + "复制成功", LOG_PATH + "/" + LOG_NAME);// 写日志
					getDirectoryFile(filePath);
					lv.setAdapter(sa);
				} else {//复制失败
					ShowToast(fileName + "复制失败！");
					// 复制失败时清除已经复制的部分文件
					fo.deleteFile(new File(path));
//					fo.writeLogFile(tool.CountDate(System.currentTimeMillis())
//							+ " " + oldPath + "/" + fileName + "复制到" + path
//							+ "  " + "复制失败", LOG_PATH + "/" + LOG_NAME);// 写日志
					getDirectoryFile(filePath);
					lv.setAdapter(sa);
				}
				fileName = null;
				oldPath = null;
				copyOrMove = 0;
				bt5.setVisibility(View.GONE);
				bt6.setVisibility(View.GONE);// 移动完成后按钮消失
				bt4.setEnabled(true);
//				download.setEnabled(true);
				if (pd != null && pd.isShowing()) {
					pd.dismiss();
					pd.setProgress(0);
				}
				break;
			case 0x234://移动完成时
				String path1 = msg.obj.toString();
				if (msg.arg1 == 1) {
					ShowToast(fileName + "移动成功！");
//					fo.writeLogFile(tool.CountDate(System.currentTimeMillis())
//							+ " " + oldPath + "/" + fileName + "移动到" + path1
//							+ "  " + "移动成功", LOG_PATH + "/" + LOG_NAME);// 写日志
					getDirectoryFile(filePath);
					lv.setAdapter(sa);
				} else {
					ShowToast(fileName + "移动失败！");
//					fo.writeLogFile(tool.CountDate(System.currentTimeMillis())
//							+ " " + oldPath + "/" + fileName + "移动到" + path1
//							+ "  " + "移动失败", LOG_PATH + "/" + LOG_NAME);// 写日志
					getDirectoryFile(filePath);
					lv.setAdapter(sa);
				}
				fileName = null;
				oldPath = null;
				copyOrMove = 0;
				bt5.setVisibility(View.GONE);
				bt6.setVisibility(View.GONE);// 移动完成后按钮消失
				bt4.setEnabled(true);
//				download.setEnabled(true);
				if (pd != null && pd.isShowing())
					pd.dismiss();
				break;
			case 0x111://复制/移动时显示ProgressDialog
				if (pd != null && pd.isShowing()) {
					pd.setProgress(msg.arg1);
				}
				break;
//			case 0x135://用于处理资源已经存在的情况
//				obj = msg.obj.toString();
//				index = Integer
//						.valueOf(obj.substring(obj.lastIndexOf('-') + 1));
//				TextView title;
//				title = new TextView(FileActivity.this);
//				title.setText("资源已存在，确定重新下载？");
//				title.setTextColor(Color.rgb(51, 181, 229));
//				title.setTextSize(20);
//				title.setGravity(Gravity.CENTER);
//				new AlertDialog.Builder(FileActivity.this)
//						.setCancelable(false)
//						.setCustomTitle(title)
//						.setPositiveButton("确定",
//								new DialogInterface.OnClickListener() {
//
//									@Override
//									public void onClick(DialogInterface dialog,
//											int which) {
//										// TODO 自动生成的方法存根
//										String file = DOWNLOAD_PATH
//												+ "/"
//												+ downloadMap.get(index).get(
//														"DownloadName");
//										fo.deleteFile(new File(file));
//										dt.get(index).setFinished(false);
//
//									}
//								})
//						.setNegativeButton("取消",
//								new DialogInterface.OnClickListener() {
//
//									@Override
//									public void onClick(DialogInterface dialog,
//											int which) {
//										// TODO 自动生成的方法存根
//										// 启动
//										dt.get(index).setDestory(true);// 销毁线程
//										if (index != downloadMap.size() - 1) {// 重命名
//											for (int i = index + 1; i < downloadMap
//													.size(); i++) {
//												dt.get(i).setName(
//														"DownloadThread-"
//																+ (i - 1));
//											}
//										}
//										dt.remove(index);
//										downloadMap.remove(index);
//										lv.setAdapter(downloadSa);// 刷新
//									}
//								}).show();
//				break;
			default:
				break;
			}
			super.handleMessage(msg);
		}
	};

	public void Init() {

		copyOrMove = 0;
		oldPath = null;
		fileName = null;
		isSave = false;
//		isDelete = true;
		// 数据初始化
		lv = (ListView) findViewById(R.id.lv);
		tv = (TextView) findViewById(R.id.tv);
		bt1 = (Button) findViewById(R.id.bt1);
		bt2 = (Button) findViewById(R.id.bt2);
		bt3 = (Button) findViewById(R.id.bt3);
		bt4 = (Button) findViewById(R.id.bt4);
		bt5 = (Button) findViewById(R.id.bt5);
		bt6 = (Button) findViewById(R.id.bt6);

//		add = (Button) findViewById(R.id.add);
//		download = (Button) findViewById(R.id.download);

		fo = new FileOperation();
		root = Environment.getExternalStorageDirectory().getPath();

		fileMap = new ArrayList<HashMap<String, Object>>();

//		logMap = new ArrayList<HashMap<String, Object>>();

//		downloadMap = new ArrayList<HashMap<String, Object>>();

		sp = this.getPreferences(MODE_PRIVATE );//| MODE_MULTI_PROCESS

		ed = sp.edit();
		filePath = sp.getString("Path", root);
		oldFilePath = filePath;
		tv.setText(filePath);
		// 如果日至不存在 创建日志文件
//		fo.newFileAndFolder(LOG_PATH, LOG_NAME);
		tool = new Tools();

//		LogView = false;
		DownloadView = false;
//		// 下载文件存储路径
//		fo.newFolder(DOWNLOAD_PATH);

		sa = new SimpleAdapter(this, fileMap, R.layout.list, new String[] {
				"FileImage", "FileText", "FileName", "type" }, new int[] {
				R.id.iv, R.id.tv2, R.id.tv1, R.id.tv3 });

//		// 日志的SimpleAdapter
//		logSa = new SimpleAdapter(this, logMap, R.layout.loglist, new String[] {
//				"Number", "Log" }, new int[] { R.id.text1, R.id.text2 });
//		// 下载的MyAdapter
//		downloadSa = new MyAdapter(this, downloadMap);
//		dt = new ArrayList<DownloadThread>();
//
//		// 数据库 用于存储上一次的下载记录
//		dataHelper = new DataHelper(this);

		getDirectoryFile(filePath);// 赋值

		if (root.equals(filePath)) {
			bt2.setEnabled(false);
		}

	}
	protected class OnMiddleImageButtonClickListener implements
	onMiddleImageButtonClickListener {
		@Override
		public void onClick() {
		}
	}
	private class OnRightImageButtonClickListener implements
	onRightImageButtonClickListener {
		@Override
		public void onClick() {
			String code = "暂未选择文件,确认退出？";
//			if (dt != null && dt.size() != 0) {
//				code = "还有" + dt.size() + "项任务下载中,确认退出？";
//			}
			new AlertDialog.Builder(mContext)
					.setCancelable(false)
					.setIcon(R.drawable.info)
					.setTitle(code)
					.setPositiveButton("确认",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO 自动生成的方法存根
									finish();
								}
							}).setNegativeButton("取消", null).show();
		}
	}
	private void onExit(String originalpath) {
		Intent intent = new Intent();
		intent.putExtra("filepath", originalpath);
		setResult(2, intent);
		finish();
	}
	@Override
	public void onCreate(Bundle savedInstanceState) {
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_file);
		mContext = this;
		mHeaderLayout = (HeaderLayout) findViewById(R.id.title_bar);
		
//		mHeaderLayout.init(HeaderStyle.TITLE_CHAT);
//		mHeaderLayout.setTitleChat(R.drawable.ic_chat_dis_1,
//				R.drawable.bg_chat_dis_active, "Show一下",
//				"",
//				R.drawable.addynamics,//ic_menu_invite  ic_topbar_profile
//				new OnMiddleImageButtonClickListener(),
//				R.drawable.return2,
//				new OnRightImageButtonClickListener());
		
        mHeaderLayout.init(HeaderStyle.TITLE_RIGHT_IMAGEBUTTON);
		mHeaderLayout.setTitleRightImageButton("选择文件", null,
				R.drawable.return2,
				new OnRightImageButtonClickListener());
		
		
		Init();

		bt1.setOnClickListener(this);
		bt2.setOnClickListener(this);
		bt3.setOnClickListener(this);
		bt4.setOnClickListener(this);
		bt5.setOnClickListener(this);
		bt6.setOnClickListener(this);
//
//		download.setOnClickListener(this);
//		add.setOnClickListener(this);
//		// ib.setOnClickListener(this);
		/*
		 * 
		 * 绑定并显示
		 */
		lv.setAdapter(sa);

		/*
		 * 
		 * 绑定监听
		 */
		lv.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				// TODO 自动生成的方法存根
				if ( !DownloadView) {//!LogView &&
					if (fileMap.get(arg2).get("type").toString().equals("文件夹")) {// 点击了文件夹
						filePath = filePath + "/"
								+ fileMap.get(arg2).get("FileName");
						getDirectoryFile(filePath);// 赋值
						tv.setText(filePath);
						lv.setAdapter(sa);
						if (!root.equals(filePath)) {
							bt2.setEnabled(true);
						}
					} else {// 点击了者文件
//						OpenFileImpl(fileMap.get(arg2).get("FileName")
//								.toString());//可以添加预览文件功能
						onExit(filePath + "/" +fileMap.get(arg2).get("FileName")
								.toString());
					}
				}
//				else if (DownloadView) {
//					int id = R.drawable.info;
//					final int index = arg2;
//					final Button bt = (Button) arg1.findViewById(R.id.ib);
//					bt.setBackgroundResource(R.drawable.down);
//					FileActivity.dt.get(index).setState(false);
//					new AlertDialog.Builder(FileActivity.this)
//							.setCancelable(false)
//							.setIcon(id)
//							.setTitle("确认删除？")
//							.setMultiChoiceItems(
//									new String[] { "删除已下载文件" },
//									new boolean[] { true },
//									new DialogInterface.OnMultiChoiceClickListener() {
//										@Override
//										public void onClick(
//												DialogInterface dialog,
//												int which, boolean isChecked) {
//											// TODO 自动生成的方法存根
//											isDelete = isChecked;
//										}
//									})
//							.setPositiveButton("确定",
//									new DialogInterface.OnClickListener() {
//
//										@Override
//										public void onClick(
//												DialogInterface dialog,
//												int which) {
//											// TODO 自动生成的方法存根
//											String file = DOWNLOAD_PATH
//													+ "/"
//													+ downloadMap
//															.get(index)
//															.get("DownloadName");
//											dt.get(index).setDestory(true);// 销毁线程
//											if (index != downloadMap.size() - 1) {// 重命名
//												for (int i = index + 1; i < downloadMap
//														.size(); i++) {
//													dt.get(i).setName(
//															"DownloadThread-"
//																	+ (i - 1));
//												}
//											}
//											dt.remove(index);
//											downloadMap.remove(index);
//											lv.setAdapter(downloadSa);// 刷新
//											if (isDelete) {
//												fo.deleteFile(new File(file));
//											}
//										}
//									})
//							.setNegativeButton("取消",
//									new DialogInterface.OnClickListener() {
//
//										@Override
//										public void onClick(
//												DialogInterface dialog,
//												int which) {
//											// TODO 自动生成的方法存根
//											// 启动
//											bt.setBackgroundResource(R.drawable.pause);
//											FileActivity.dt.get(index)
//													.setState(true);
//										}
//									}).show();
//				}
			}

		});

		/*
		 * 
		 * 绑定长按监听
		 */
		lv.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {
				// TODO Auto-generated method stub
				if (!DownloadView) {//!LogView && 
					final int attr = position;
					new AlertDialog.Builder(FileActivity.this)
							.setIcon(R.drawable.info)
							.setTitle("列表框")
							.setItems(new String[] { "删除", "移动", "复制", "大小" },
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											// TODO Auto-generated method stub
											if (oldPath == null
													&& fileName == null) {
												switch (which) {
												case 0:
													String path = filePath
															+ "/"
															+ fileMap
																	.get(attr)
																	.get("FileName");
													String name = fileMap
															.get(attr)
															.get("FileName")
															.toString();
													if (fo.deleteFile(new File(
															path))) {
														ShowToast(name
																+ "删除成功!");
//														fo.writeLogFile(
//																tool.CountDate(System
//																		.currentTimeMillis())
//																		+ " "
//																		+ path
//																		+ " "
//																		+ fileMap
//																				.get(attr)
//																				.get("type")
//																		+ "  "
//																		+ "删除成功",
//																LOG_PATH
//																		+ "/"
//																		+ LOG_NAME);// 写日志
														getDirectoryFile(filePath);
														lv.setAdapter(sa);
													} else {
														ShowToast(name
																+ "删除失败!");

//														fo.writeLogFile(
//																tool.CountDate(System
//																		.currentTimeMillis())
//																		+ " "
//																		+ path
//																		+ " "
//																		+ fileMap
//																				.get(attr)
//																				.get("type")
//																		+ "  "
//																		+ "删除失败",
//																LOG_PATH
//																		+ "/"
//																		+ LOG_NAME);// 写日志
														getDirectoryFile(filePath);
														lv.setAdapter(sa);
													}
													break;
												case 1:
													bt4.setEnabled(false);
//													download.setEnabled(false);
													copyOrMove = 1;
													bt5.setVisibility(View.VISIBLE);
													bt6.setVisibility(View.VISIBLE);
													oldPath = filePath;
													fileName = fileMap
															.get(attr)
															.get("FileName")
															.toString();
													break;
												case 2:
													bt4.setEnabled(false);
//													download.setEnabled(false);
													copyOrMove = 2;
													bt5.setVisibility(View.VISIBLE);
													bt6.setVisibility(View.VISIBLE);
													oldPath = filePath;
													fileName = fileMap
															.get(attr)
															.get("FileName")
															.toString();
													break;
												case 3:
													String name1 = fileMap
															.get(attr)
															.get("FileName")
															.toString();
													String path1 = filePath
															+ "/" + name1;
													if (fileMap.get(attr)
															.get("type")
															.toString()
															.equals("文件夹")) {
														ShowToast(name1
																+ "文件夹大小为："
																+ Tools.FormetFileSize(Tools
																		.getDirectorySize(new File(
																				path1))));
													} else {
														ShowToast(name1
																+ "文件大小为："
																+ Tools.FormetFileSize(new File(
																		path1)
																		.length()));
													}
													break;
												default:
													break;
												}
											} else {
												ShowToast("请先完成其他操作!");
											}
										}
									}).show();
				}
				return false;
			}
		});
	}

	@Override
	protected void onStart() {
		// TODO 自动生成的方法存根
//		sd = dataHelper.getWritableDatabase();
		isSave = false;
//		downloadMapInit();
//		// 取出上一次的数据并清空数据库
//		sd.delete("downloadInfo", null, null);
		super.onStart();
	}

//	public void downloadMapInit() {
//		Cursor cursor = sd
//				.query("downloadInfo", new String[] { "url", "isFinish",
//						"fileName", "downloaded", "threadNum", "fileSize" },
//						null, null, null, null, "id");
//		int i = 0;
//		while (cursor.moveToNext()) {
//			HashMap<String, Object> hm = new HashMap<String, Object>();
//			final String url = cursor.getString(0);
//
//			hm.put("DownloadName", Tools.getFileName(url));
//
//			hm.put("Progress", Tools.getProportion(
//					String.valueOf(cursor.getInt(5)), cursor.getInt(3)));
//
//			hm.put("Size", cursor.getInt(5));
//
//			String finish[] = cursor.getString(1).split("[?]");
//
//			final int downloaded[] = new int[finish.length];
//
//			final boolean isf[] = new boolean[finish.length];
//
//			for (int j = 0; j < finish.length; j++) {
//				String[] flag = finish[j].split("_");
//				downloaded[j] = Integer.valueOf(flag[1]);
//				if (flag[0].equals("1")) {
//					isf[j] = true;
//				} else {
//					isf[j] = false;
//				}
//			}
//			final int k = i;
//			final int threadNum = cursor.getInt(4);
//			final String fname = cursor.getString(2);
//			final int down = cursor.getInt(3);
//			new Thread(new Runnable() {
//
//				@Override
//				public void run() {
//					// TODO 自动生成的方法存根
//					DownloadThread dThread = new DownloadThread(url, threadNum,
//							DOWNLOAD_PATH + "/" + fname, handler, isf, down,
//							downloaded);
//					dThread.setName("DownloadThread-" + k);
//					dt.add(dThread);
//					dThread.run();
//				}
//			}).start();
//			downloadMap.add(hm);
//			i++;
//		}
//		cursor.close();
//	}

	//
	@Override
	public void onClick(View v) {
		// TODO 自动生成的方法存根
		switch (v.getId()) {
		case R.id.bt1:
			bt2.setEnabled(false);
			if (DownloadView) {//LogView || 
				bt3.setEnabled(true);
			}
			if (DownloadView)
				bt5.setVisibility(View.GONE);
//			add.setVisibility(View.GONE);
			filePath = root;
			getDirectoryFile(filePath);// 赋值
			lv.setAdapter(sa);
			tv.setText(filePath);
//			LogView = false;
			DownloadView = false;
			break;
		case R.id.bt2:
			if (!DownloadView) {//!LogView && 
				filePath = filePath.substring(0, filePath.lastIndexOf("/"));
				tv.setText(filePath);
				getDirectoryFile(filePath);// 赋值
				lv.setAdapter(sa);
				if (root.equals(filePath)) {
					bt2.setEnabled(false);
				}
			}
			break;
		case R.id.bt3:
			if ( !DownloadView) {//!LogView &&
				final EditText et = new EditText(this);
				new AlertDialog.Builder(this)
						.setCancelable(false)
						.setIcon(R.drawable.info)
						.setTitle("请输入文件夹名称")
						.setView(et)
						.setPositiveButton("确定",
								new DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface dialog,
											int which) {
										// TODO 自动生成的方法存根
										if (et.getText().toString() != null
												&& !et.getText().toString()
														.equals("")) {
											fo.newFolder(filePath + "/"
													+ et.getText().toString());
											getDirectoryFile(filePath);// 赋值
											lv.setAdapter(sa);
//											fo.writeLogFile(
//													tool.CountDate(System
//															.currentTimeMillis())
//															+ " "
//															+ filePath
//															+ "/"
//															+ et.getText()
//																	.toString()
//															+ " 文件夹"
//															+ "  "
//															+ "创建文件夹", LOG_PATH
//															+ "/" + LOG_NAME);// 写日志

										}
									}
								}).setNegativeButton("取消", null).show();
			}
			break;
		case R.id.bt4:
			if (copyOrMove == 0) {
				bt2.setEnabled(false);
				bt3.setEnabled(false);
				if (DownloadView)
					bt5.setVisibility(View.GONE);
//				add.setVisibility(View.GONE);
//				logMap.clear();
//				String[] log = fo.readLogFile(LOG_PATH + "/" + LOG_NAME);
//
//				for (int i = 0; i < log.length; i++) {
//					HashMap<String, Object> hm = new HashMap<String, Object>();
//					hm.put("Number", i + 1);
//					hm.put("Log", log[i]);
//					logMap.add(hm);
//				}
//				lv.setAdapter(logSa);// 显示
//				LogView = true;
				DownloadView = false;
			} else if (copyOrMove == 1) {
				ShowToast("请先完成移动或者取消移动！");
			} else {
				ShowToast("请先完成复制或者取消复制！");
			}
			break;
		case R.id.bt5:
			bt4.setEnabled(true);
//			download.setEnabled(true);
			fileName = null;
			oldPath = null;
			copyOrMove = 0;
			bt5.setVisibility(View.GONE);
			bt6.setVisibility(View.GONE);
			break;
		case R.id.bt6:
			final String path = filePath + "/" + fileName;
			if (copyOrMove == 1) {
				if(!oldPath.equals(filePath)){
					pd = new ProgressDialog(this);
					pd.setProgressStyle(ProgressDialog.STYLE_SPINNER);
					pd.setMessage("移动中");
					pd.setIndeterminate(true);
					pd.setCancelable(false);
					if (pd != null && !pd.isShowing()) {
						pd.show();
					}
					new Thread(new Runnable() {
						@Override
						public void run() {
							// TODO 自动生成的方法存根
							boolean isSuccess = fo.moveFile(oldPath + "/"
									+ fileName, path);
							Message msg = Message.obtain();
							if (isSuccess == false) {
								msg.arg1 = 0;
							} else {
								msg.arg1 = 1;
							}
							msg.what = 0x234;
							msg.obj = path;
							handler.sendMessage(msg);
						}
					}).start();
				}else{
					fileName = null;
					oldPath = null;
					copyOrMove = 0;
					bt5.setVisibility(View.GONE);
					bt6.setVisibility(View.GONE);// 移动完成后按钮消失
					bt4.setEnabled(true);
//					download.setEnabled(true);
					ShowToast("文件路径一致，不需要移动！"); 
				}
			} else if (copyOrMove == 2) {
				if(!oldPath.equals(filePath)){
					pd = new ProgressDialog(this);
					pd.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					pd.setMessage("复制中");
					pd.setIndeterminate(false);
					pd.setCancelable(false);
					pd.setMax(100);
					final FileOperation foo = new FileOperation(handler, oldPath
							+ "/" + fileName);
					if (pd != null && !pd.isShowing()) {
						pd.show();
					}
					new Thread(new Runnable() {
						@Override
						public void run() {
							// TODO 自动生成的方法存根
							boolean isSuccess = foo.copyFloder(oldPath + "/"
									+ fileName, filePath);
							Message msg = Message.obtain();
							if (isSuccess == false) {
								msg.arg1 = 0;
							} else {
								msg.arg1 = 1;
							}
							msg.what = 0x123;
							msg.obj = path;
							handler.sendMessage(msg);
						}
					}).start();
				}else{
					fileName = null;
					oldPath = null;
					copyOrMove = 0;
					bt5.setVisibility(View.GONE);
					bt6.setVisibility(View.GONE);// 移动完成后按钮消失
					bt4.setEnabled(true);
//					download.setEnabled(true);
					ShowToast("文件路径一致，不需要复制！");
				}
			}
			break;
//		case R.id.add:
//			final EditText et = new EditText(this);
//			new AlertDialog.Builder(this)
//					.setCancelable(false)
//					.setIcon(R.drawable.info)
//					.setTitle("请输入下载地址")
//					.setView(et)
//					.setPositiveButton("确定",
//							new DialogInterface.OnClickListener() {
//								@Override
//								public void onClick(DialogInterface dialog,
//										int which) {
//									// TODO 自动生成的方法存根
//									final String url = et.getEditableText()
//											.toString();
//									if (isExistUrl(url)) {
//										ShowToast("该资源正在下载中，请勿重复添加！");
//									} else {
//										int num = 5;// 线程数目
//										if (url != null && !url.equals("")) {
//											// 进行下载
//											HashMap<String, Object> a = new HashMap<String, Object>();
//											final String name = Tools
//													.getFileName(url);
//											if (name != null
//													&& !name.equals("")
//													&& checkName(name)) {
//												ShowToast(name + "下载中");
//												a.put("DownloadName", name);
//												a.put("Size", 0);
//
//												a.put("Progress", 0);
//												downloadMap.add(a);
//												final boolean isFinish[] = new boolean[num];
//												for (int i = 0; i < num; i++) {
//													isFinish[i] = false;
//												}
//												new Thread(new Runnable() {
//
//													@Override
//													public void run() {
//														// TODO 自动生成的方法存根
//														DownloadThread dThread = new DownloadThread(
//																url, 5,
//																DOWNLOAD_PATH
//																		+ "/"
//																		+ name,
//																handler,
//																isFinish, 0,
//																null);
//														dThread.setName("DownloadThread-"
//																+ (downloadMap
//																		.size() - 1));
//														dt.add(dThread);
//														dThread.run();
//													}
//												}).start();
//												lv.setAdapter(downloadSa);
//											} else {
//												if (!checkNetWorkStatus()) {
//													ShowToast("无网络连接！");
//												} else {
//													ShowToast("下载链接无效！");
//												}
//											}
//										} else {
//											ShowToast("地址不能为空");
//										}
//									}
//								}
//							}).setNegativeButton("取消", null).show();
//			break;
//		case R.id.download:
//			if (copyOrMove == 0) {// 非移动和复制
//				bt2.setEnabled(false);
//				bt3.setEnabled(false);
//				bt5.setVisibility(View.INVISIBLE);
//				add.setVisibility(View.VISIBLE);
//				lv.setAdapter(downloadSa);
//				DownloadView = true;
//				LogView = false;
//			} else if (copyOrMove == 1) {
//				ShowToast("请先完成移动或者取消移动！");
//			} else {
//				ShowToast("请先完成复制或者取消复制！");
//			}
//			break;
		default:
			break;
		}
	}

	public void ShowToast(String arg) {
		if (mToast != null) {
			mToast.cancel();
		}
		mToast = Toast.makeText(this, arg, Toast.LENGTH_SHORT);
		mToast.show();
	}

//	public boolean isExistUrl(String url) {
//		for (int i = 0; i < dt.size(); i++) {
//			if (url.equals(dt.get(i).getUrl())) {
//				return true;
//			}
//		}
//		return false;
//	}

	/*
	 * 
	 * 数据拉入
	 */
	public void getDirectoryFile(String path) {
		File f = new File(path);
		if (f.exists()) {
			File[] son = f.listFiles();
			if (son != null) {
				oldFilePath = filePath;
				fileMap.clear();
				for (File fi : son) {
					HashMap<String, Object> map = new HashMap<String, Object>();
					if (!fi.isFile()) {// 目录
						map.put("FileImage", R.drawable.wenjianjia);// 图像资源的ID
						map.put("FileText", fi.getPath());
						map.put("FileName", fi.getName());
						map.put("type", "文件夹");
					} else {// 文件
						map.put("FileText", tool.CountDate(fi.lastModified())
								+ " " + Tools.FormetFileSize(fi.length()));
						map.put("FileName", fi.getName());
						String fileName = fi.getName();
						if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingImage))) {// pic

							map.put("FileImage", R.drawable.pic);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingWebText))) {

							map.put("FileImage", R.drawable.html);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingPackage))) {
							map.put("FileImage", R.drawable.apk);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingAudio))) {

							map.put("FileImage", R.drawable.music);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingVideo))) {

							map.put("FileImage", R.drawable.video);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingText))) {

							map.put("FileImage", R.drawable.text);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingPdf))) {

							map.put("FileImage", R.drawable.pdf);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingWord))) {

							map.put("FileImage", R.drawable.word);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingExcel))) {

							map.put("FileImage", R.drawable.excel);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingPPT))) {

							map.put("FileImage", R.drawable.ppt);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");

						} else if (OpenFile.checkEndsWithInStringArray(
								fileName,
								getResources().getStringArray(
										R.array.fileEndingOther))) {
							map.put("FileImage", R.drawable.rar);// 图像资源的ID
							map.put("type", fo.getFileType(fileName) + "文件");
						} else {
							map.put("FileImage", R.drawable.other);// 图像资源的ID
							map.put("type", "文件");
						}
					}
					fileMap.add(map);
				}

				ArrayList<HashMap<String, Object>> dirTemp = new ArrayList<HashMap<String, Object>>();
				ArrayList<HashMap<String, Object>> fileTemp = new ArrayList<HashMap<String, Object>>();
				for (int i = 0; i < fileMap.size(); i++) {
					if (fileMap.get(i).get("type").toString().equals("文件夹")) {
						dirTemp.add(fileMap.get(i));
					} else {
						fileTemp.add(fileMap.get(i));
					}
				}

				// 文件夹排序！！！
				for (int i = 0; i < dirTemp.size(); i++) {
					for (int j = 0; j < dirTemp.size(); j++) {
						HashMap<String, Object> temp;
						if (dirTemp
								.get(i)
								.get("FileName")
								.toString()
								.toLowerCase()
								.compareTo(
										dirTemp.get(j).get("FileName")
												.toString().toLowerCase()) < 1) {
							temp = dirTemp.get(j);
							dirTemp.set(j, dirTemp.get(i));
							dirTemp.set(i, temp);
						}
					}
				}

				// 文件排序！！！
				for (int i = 0; i < fileTemp.size(); i++) {
					for (int j = 0; j < fileTemp.size(); j++) {
						HashMap<String, Object> temp;
						if (fileTemp
								.get(i)
								.get("FileName")
								.toString()
								.toLowerCase()
								.compareTo(
										fileTemp.get(j).get("FileName")
												.toString().toLowerCase()) < 1) {
							temp = fileTemp.get(j);
							fileTemp.set(j, fileTemp.get(i));
							fileTemp.set(i, temp);
						}
					}
				}

				fileMap.clear();

				for (int i = 0; i < fileTemp.size() + dirTemp.size(); i++) {
					if (i < dirTemp.size()) {
						fileMap.add(dirTemp.get(i));
					} else {
						fileMap.add(fileTemp.get(i - dirTemp.size()));
					}
				}
				fileTemp = null;
				dirTemp = null;
			} else {// 进入不了文件夹
				filePath = oldFilePath;
			}
		} else {
			filePath = oldFilePath;
		}
		filePath = oldFilePath;
	}

	/*
	 * 
	 * 传入文件路径
	 */
	public void OpenFileImpl(String name) {
		File file = new File(filePath + "/" + name);
		if (file != null && file.isFile()) {
			String fileName = file.getName();
			Intent intent;
			if (OpenFile.checkEndsWithInStringArray(fileName, getResources()
					.getStringArray(R.array.fileEndingImage))) {
				intent = OpenFile.getImageFileIntent(file);
				startActivity(intent);
			} else if (OpenFile.checkEndsWithInStringArray(fileName,
					getResources().getStringArray(R.array.fileEndingWebText))) {
				intent = OpenFile.getHtmlFileIntent(file);
				startActivity(intent);
			} else if (OpenFile.checkEndsWithInStringArray(fileName,
					getResources().getStringArray(R.array.fileEndingPackage))) {
				intent = OpenFile.getApkFileIntent(file);
				startActivity(intent);

			} else if (OpenFile.checkEndsWithInStringArray(fileName,
					getResources().getStringArray(R.array.fileEndingAudio))) {
				intent = OpenFile.getAudioFileIntent(file);
				startActivity(intent);
			} else if (OpenFile.checkEndsWithInStringArray(fileName,
					getResources().getStringArray(R.array.fileEndingVideo))) {
				intent = OpenFile.getVideoFileIntent(file);
				startActivity(intent);
			} else if (OpenFile.checkEndsWithInStringArray(fileName,
					getResources().getStringArray(R.array.fileEndingText))) {
				intent = OpenFile.getTextFileIntent(file);
				startActivity(intent);
			} else if (OpenFile.checkEndsWithInStringArray(fileName,
					getResources().getStringArray(R.array.fileEndingPdf))) {
				intent = OpenFile.getPdfFileIntent(file);
				startActivity(intent);
			} else if (OpenFile.checkEndsWithInStringArray(fileName,
					getResources().getStringArray(R.array.fileEndingWord))) {
				intent = OpenFile.getWordFileIntent(file);
				startActivity(intent);
			} else if (OpenFile.checkEndsWithInStringArray(fileName,
					getResources().getStringArray(R.array.fileEndingExcel))) {
				intent = OpenFile.getExcelFileIntent(file);
				startActivity(intent);
			} else if (OpenFile.checkEndsWithInStringArray(fileName,
					getResources().getStringArray(R.array.fileEndingPPT))) {
				intent = OpenFile.getPPTFileIntent(file);
				startActivity(intent);
			} else {// 其他文件
				intent = OpenFile.getOtherFileIntent(file);
				startActivity(intent);
			}
		} else {
			ShowToast("对不起，这不是文件！");
		}
	}

	public boolean checkName(String name) {
		if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingImage))) {
			return true;
		} else if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingWebText))) {
			return true;
		} else if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingPackage))) {
			return true;

		} else if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingAudio))) {
			return true;
		} else if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingVideo))) {
			return true;
		} else if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingText))) {
			return true;
		} else if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingPdf))) {
			return true;
		} else if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingWord))) {
			return true;
		} else if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingExcel))) {
			return true;
		} else if (OpenFile.checkEndsWithInStringArray(name, getResources()
				.getStringArray(R.array.fileEndingPPT))) {
			return true;
		} else {// 其他文件
			return false;
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		// 正常退出程序时存储数据

		super.onPause();
	}

	@Override
	protected void onDestroy() {
		// TODO Auto-generated method stub
		ed.putString("Path", filePath);
		ed.commit();
//		if (!isSave) {
//			if (downloadMap != null) {
//				for (int i = 0; i < dt.size(); i++) {
//					dt.get(i).setDestory(true);
//				}
//				for (int i = 0; i < downloadMap.size(); i++) {
//
//					ContentValues cv = new ContentValues();
//
//					boolean[] isf = dt.get(i).getIsFinish();
//
//					int[] download = dt.get(i).getChildDownloaded();
//
//					int size = dt.get(i).getFileSize();
//
//					int downloaded1 = dt.get(i).getDownloadedSize();
//
//					int downloaded = 0;
//
//					String finish = "";
//
//					for (int j = 0; j < isf.length; j++) {
//						if (isf[j])
//							finish = finish + 1 + "_" + download[j] + "?";
//						else
//							finish = finish + 0 + "_" + download[j] + "?";
//						downloaded = downloaded + download[j];
//					}
//					finish = finish.substring(0, finish.length() - 1);
//
//					cv.put("url", dt.get(i).getUrl());
//					cv.put("isFinish", finish);
//					cv.put("fileName", downloadMap.get(i).get("DownloadName")
//							.toString());
//					cv.put("downloaded", downloaded);
//					cv.put("fileSize", size);
//					cv.put("threadNum", dt.get(i).getThreadNum());
//					sd.insert("downloadInfo", "id", cv);
//				}
//			}
//			isSave = true;
//			sd.close();
//		}
//		dt = null;
//		downloadMap = null;
//		logMap = null;
		fileMap = null;
		handler = null;
		super.onDestroy();
	}

	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// TODO 自动生成的方法存根
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			String code = "暂未选择文件,确认退出？";
//			if (dt != null && dt.size() != 0) {
//				code = "还有" + dt.size() + "项任务下载中,确认退出？";
//			}
			new AlertDialog.Builder(this)
					.setCancelable(false)
					.setIcon(R.drawable.info)
					.setTitle(code)
					.setPositiveButton("确认",
							new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog,
										int which) {
									// TODO 自动生成的方法存根
									finish();
								}
							}).setNegativeButton("取消", null).show();
		}
		return super.onKeyUp(keyCode, event);
	}

	public boolean checkNetWorkStatus() {
		boolean result;
		ConnectivityManager cm = (ConnectivityManager) this
				.getSystemService(this.CONNECTIVITY_SERVICE);
		NetworkInfo netinfo = cm.getActiveNetworkInfo();
		if (netinfo != null) {
			result = true;
		} else {
			result = false;
		}
		return result;
	}
}